import { message } from "antd"
import ky from "ky"

import { useTokenStroe } from "~store/tokenStore"
import { getStyleContainerRoot } from "~util"

import { OIAItype, OIAItypeObj } from "./AIUtil"

export const request = ky.create({
  retry: 0,
  hooks: {
    beforeRequest: [
      async (req, options) => {
        const tokenType = useTokenStroe.getState().tokenType
        const token = useTokenStroe.getState().accessToken.access_token
        req.headers.set("Content-Type", "application/json")
        switch (tokenType.aiSource) {
          case OIAItypeObj.baidu.type:
            if (token && token.trim()) {
              req.headers.set("Authorization", token)
            }
            break
          case OIAItypeObj.chatgpt.type:
            if (token && token.trim()) {
              req.headers.set("Authorization", `Bearer ${token}`)
            }
            break
        }
      }
    ],
    afterResponse: [
      async (req, options, res) => {
        const header = res.headers.get("Content-Type")

        if (res.status != 200) {
          try {
            const json = await res.json()
            const newres = new Response(JSON.stringify(json), {
              status: 200,
              headers: {
                "Content-Type": "application/json"
              }
            })
            return newres
          } catch (err) {
            const newres = new Response(
              JSON.stringify({ error: err.message }),
              {
                status: 200,
                headers: {
                  "Content-Type": "application/json"
                }
              }
            )
            return newres
          }
        }
      }
    ],
    beforeError: [
      async (error) => {
        // console.log("error", error)
        return error
      }
    ]
  }
})
